package com.cx330;

import org.junit.Test;

public class Example55 {
    @Test
    public void testString() {
        long start = System.currentTimeMillis();
        String s = new String("0");
        for (int i = 1; i <= 100000; i++) {
            s += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("String拼接+用时：" + (end - start)); // 2714
        long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.out.println("String拼接+memory占用内存：" + memory); // 419610200
    }

    @Test
    public void testStringBuffer() {
        long start = System.currentTimeMillis();
        StringBuffer s = new StringBuffer("0");
        for (int i = 1; i <= 100000; i++) {
            s.append(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("StringBuffer拼接+用时：" + (end - start)); // 7
        long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.out.println("StringBuffer拼接+memory占用内存：" + memory); // 10991152
    }

    @Test
    public void  testStringBuilder() {
        long start = System.currentTimeMillis();;
        StringBuilder s = new StringBuilder("0");
        for (int i = 1; i <= 100000; i++) {
            s.append(i);
        }
        long end = System.currentTimeMillis();
        System.out.println("StringBuilder拼接+用时：" + (end - start)); // 5
        long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.out.println("StringBuilder拼接+memory占用内存：" + memory); // 11108368
    }
}
